package com.aduerr.v1shouyin.mvp.activity;

import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import com.aduerr.v1shouyin.R;
import com.aduerr.v1shouyin.common.Constants;
import com.aduerr.v1shouyin.entity.*;
import com.aduerr.v1shouyin.http.APIRetrofit;
import com.aduerr.v1shouyin.http.RXRequest;
import com.aduerr.v1shouyin.util.ToastUtils;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.internal.observers.BlockingBaseObserver;
import io.reactivex.schedulers.Schedulers;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.List;


/**
 * @author HI
 * @email dev1024@foxmail.com
 * @time 2018/10/18 10:33
 * @change
 * @chang time
 * @class describe
 */

public class HandInputActivity extends AppCompatActivity {

    private static final String TAG = "HandInputActivity";

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_order)
    TextView tvOrder;
    @BindView(R.id.et_order)
    EditText etOrder;
    @BindView(R.id.tv_error)
    TextView tvError;
    @BindView(R.id.tv_num)
    TextView tvNum;

    private int captureType;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hand_input);
        ButterKnife.bind(this);
        init();
    }

    void init() {
        captureType = getIntent().getIntExtra(Constants.QRCODE_CAPUTER,
                Constants.SCANCODECOLLECTION_QR);
        switch(captureType) {
            case Constants.CARD_COUPONS_VERIFY_QR://卡券核销
                tvTitle.setText("卡券核销");
                tvOrder.setText("请输入卡券码");
                break;
            case Constants.REFUND_QR://退款
                tvTitle.setText("订单号退款");
                tvOrder.setText("请输入订单号");
                break;
            case Constants.PUBLIC_PRAISE_DETAILS:
                tvTitle.setText("口碑核销");
                tvOrder.setText("请输入口碑卡券码");
                break;
            case Constants.PRE_AUTHO_REFUND://预授权退押
                tvTitle.setText("预授权完成/撤销");
                tvOrder.setText("请输入订单号");
                break;
        }
    }

    @OnClick({R.id.bt_confirm, R.id.img_back})
    void clicked(View v) {
        switch(v.getId()) {
            case R.id.bt_confirm:
                tvError.setVisibility(View.GONE);
                String editContent = etOrder.getText().toString();
                switch(captureType) {
                    case Constants.CARD_COUPONS_VERIFY_QR://卡券核销
                        // TODO: 2017/12/12 0012  卡券核销
                        toKaQuanDetail(editContent);
                        break;
                    case Constants.REFUND_QR://退款
                        toTuikuanDetail(editContent);
                        break;
                    case Constants.PUBLIC_PRAISE_DETAILS:
                        toKaQuanDetail(editContent);
                        break;
                    case Constants.PRE_AUTHO_REFUND:
                        Intent intent = new Intent(HandInputActivity.this,
                                PreAuthoOrderActivity.class);
                        intent.putExtra("orderid", editContent);
                        intent.putExtra("tag", "detail");
                        startActivity(intent);
                        finish();
                        break;
                }
                break;
            case R.id.img_back:
                finish();
                break;
        }
    }

    @OnTextChanged(value = R.id.et_order, callback = OnTextChanged.Callback.TEXT_CHANGED)
    void onTextChanged(CharSequence charSequence, int start, int before, int count) {

        if(before < start) {
            tvError.setVisibility(View.GONE);
        }

        if(charSequence != null) {
            int length = charSequence.toString().length();
            tvNum.setText(length + "/30");
        } else {
            tvNum.setText("0/30");
        }
    }


    //拿到扫描的卡券的详情信息
    private void toKaQuanDetail(String erWeiMaResult) {

        if(getIntent().getStringExtra("tag").equals("xianxia")) {
            if(erWeiMaResult.startsWith("21") || erWeiMaResult.startsWith("34") || erWeiMaResult.startsWith("8") || erWeiMaResult.startsWith("25")) {
                //JIUDIAN，MENPIAO KAITOUHUIYUAN
                HashMap<String, String> addParams = new HashMap<>();
                addParams.put("code", erWeiMaResult);//86008032893055438199  test
                APIRetrofit.getAPIService().getOtherCardDetail(RXRequest.getXingPosParams(addParams, this))
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(otherCardEntity -> {
                            int success = otherCardEntity.getSuccess();
                            if(success == 1) {

                                //跳转到卡券信息的详情界面
                                if(otherCardEntity != null) {
                                    Intent intent = new Intent(HandInputActivity.this,
                                            KaQuanDetailNewActivity.class);
                                    if(erWeiMaResult.startsWith("21")) {
                                        intent.putExtra("type", CardType.JIUDIAN.name());
                                    } else if(erWeiMaResult.startsWith("34")) {
                                        intent.putExtra("type",
                                                CardType.MENPIAOANDTUANGOU.name());
                                    } else if(erWeiMaResult.startsWith("25")) {
                                        intent.putExtra("type",
                                                CardType.MENPIAOANDTUANGOU.name());
                                    } else {
                                        intent.putExtra("type", CardType.LIPIN.name());
                                    }
                                    intent.putExtra("tag", "xianxia");
                                    intent.putExtra("Data", otherCardEntity);
                                    intent.putExtra("erWeiMaResult", erWeiMaResult);
                                    startActivity(intent);
                                    finish();
                                } else {
                                    tvError.setText("卡券信息不存在！");
                                    tvError.setVisibility(View.VISIBLE);
//                                    ToastUtils.showToast(HandInputActivity.this,
//                                    "没有该卡券码");
                                }

                            } else if(success == -4) {
                                //没有成功

                                String erMsg = otherCardEntity.getErrMsg();
                                ToastUtils.showToast(HandInputActivity.this, erMsg + "");
                            }

                        }, throwable -> {

                        });


            } else {
                //WX
                HashMap<String, String> addParams = new HashMap<>();
                addParams.put("scanTicketNo", erWeiMaResult);//86008032893055438199  test
                APIRetrofit.getAPIService().getKaQuanXiangQingDetail(RXRequest.getXingPosParams(addParams, this))
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(kaQuanXiangQingEntity -> {
                            int success = kaQuanXiangQingEntity.getSuccess();
                            if(success == 1) {
                                //跳转到卡券信息的详情界面

                                List<KaQuanXiangQingEntity.DataBean> data =
                                        kaQuanXiangQingEntity.getData();
                                //有数据,
                                if(data.size() > 0) {
                                    KaQuanXiangQingEntity.DataBean dataBean = data.get(0);
                                    List<KaQuanXiangQingEntity.DataBean.ListBean> list
                                            = dataBean.getList();
                                    KaQuanXiangQingEntity.DataBean.ListBean listBean =
                                            list.get(0);
//                                    if (listBean.getIsuse() == 1) {
//                                        ToastUtils.showToast(this, "该卡券已经被核销");
//                                    } else {
                                    Intent intent = new Intent(HandInputActivity.this,
                                            KaQuanDetailNewActivity.class);
                                    int type = Integer.parseInt(listBean.getType());
                                    intent.putExtra("type", CardType.WX.name());
                                    intent.putExtra("tag", "xianxia");
                                    intent.putExtra("Data", listBean);
                                    intent.putExtra("erWeiMaResult", erWeiMaResult);
                                    startActivity(intent);
                                    finish();
//                                    }
                                } else {
                                    tvError.setText("卡券信息不存在！");
                                    tvError.setVisibility(View.VISIBLE);
//                                    ToastUtils.showToast(HandInputActivity.this,
//                                    "没有该卡券码");
                                }

                            } else if(success == -4) {
                                //没有成功
                                String erMsg = kaQuanXiangQingEntity.getErrMsg();
                                ToastUtils.showToast(HandInputActivity.this, erMsg + "");
                            }

                        }, throwable -> {

                        });
            }
        } else {
            //口碑核销
            HashMap<String, String> addParams = new HashMap<>();
            addParams.put("TicketID", erWeiMaResult);//86008032893055438199  test
            APIRetrofit.getAPIService().getKouBeiquanDetail(RXRequest.getXingPosParams(addParams, this))
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(kouBeiTicktEntity -> {
                        int success = kouBeiTicktEntity.getSuccess();
                        if(success == 1) {
                            //跳转到卡券信息的详情界面

                            KouBeiTicktEntity.DataBean data = kouBeiTicktEntity.getData();
                            //有数据,
                            if(data != null) {
                                Intent intent = new Intent(HandInputActivity.this,
                                        KaQuanDetailNewActivity.class);
                                intent.putExtra("type", CardType.KOUBEI.name());
                                intent.putExtra("tag", "koubei");
                                intent.putExtra("Data", data);
                                intent.putExtra("erWeiMaResult", erWeiMaResult);
                                startActivity(intent);
                                finish();
                            } else {
                                tvError.setText("卡券信息不存在！");
                                tvError.setVisibility(View.VISIBLE);
//                                ToastUtils.showToast(HandInputActivity.this, "没有该卡券码");
                            }

                        } else if(success == -4) {
                            //没有成功
                            String erMsg = kouBeiTicktEntity.getErrMsg();
                            ToastUtils.showToast(HandInputActivity.this, erMsg + "");
                        } else {
                            ToastUtils.showToast(HandInputActivity.this,
                                    kouBeiTicktEntity.getErrMsg() + "");
                        }

                    }, throwable -> {
                    });
        }

       /*
        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("scanticketno", erWeiMaResult);//86008032893055438199  test
        APIRetrofit.getAPIService().getKaQuanXiangQingDetail(RXRequest.getXingPosParams
        (addParams, this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BlockingBaseObserver<KaQuanXiangQingEntity>() {
                    @Override
                    public void onNext(KaQuanXiangQingEntity kaQuanXiangQingEntity) {
                        //                    if (Tools.isAvailable
                        (kaQuanXiangQingEntity)) return;
                        int success = kaQuanXiangQingEntity.getSuccess();
                        if (success == 1) {
                            List<KaQuanXiangQingEntity.DataBean> data =
                            kaQuanXiangQingEntity.getData();
                            if (data.size() > 0) {
                                Intent intent = new Intent(HandInputActivity.this,
                                KaQuanDetailActivity.class);
//                                KaQuanXiangQingEntity.DataBean.ListBean listBean =
kaQuanXiangQingEntity.getData().get(0).getList().get(0);
                                intent.putExtra("date", kaQuanXiangQingEntity.getData()
                                .get(0).getList().get(0));
                                intent.putExtra("erWeiMaResult", erWeiMaResult);
                                startActivity(intent);
                                finish();
                            } else {
//                                ToastUtils.showToast(HandInputActivity.this,
"卡券信息不存在！");
                                tvError.setText("卡券信息不存在！");
                                tvError.setVisibility(View.VISIBLE);
                            }

                        } else if (success == -100 | success == -200) {
                            //// TODO: 2017/12/9 0009 绑定guid  界面
                            startActivity(new Intent(HandInputActivity.this,
                            BangGuidActivity.class));
                            finish();
                        } else if (success == -300 || success == -2 || success == -3 ||
                         success == -6) {
                            //// TODO: 2017/12/9 0009 去登录的界面
                            com.blankj.utilcode.util.ToastUtils.showShortSafe
                            (kaQuanXiangQingEntity.getErrMsg());
                            //扫码错误，弹出提示且关闭
                            finish();
                        } else if (success == -4) {
                            //没有成功
                            String erMsg = kaQuanXiangQingEntity.getErrMsg();
                            ToastUtils.showToast(HandInputActivity.this, erMsg + "");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (e instanceof SocketTimeoutException) {
                            Toast.makeText(HandInputActivity.this, "网络连接超时", Toast
                            .LENGTH_SHORT).show();
                        } else if (e instanceof ConnectException) {
                            Toast.makeText(HandInputActivity.this, "连接失败", Toast
                            .LENGTH_SHORT).show();
                        } else if (e instanceof UnknownHostException) {
                            Log.e("onError:", "error:-----" + e.getMessage());//R
                            .string.checknet +
                            Toast.makeText(HandInputActivity.this, "检查网络状态", Toast
                            .LENGTH_SHORT).show();
                        } else {
                            Log.e("onError:", "error:" + e.getMessage());//R.string
                            .checknet +
                            Toast.makeText(HandInputActivity.this, "检查网络状态", Toast
                            .LENGTH_SHORT).show();
                        }
                    }
                });*/
    }

    private void toTuikuanDetail(String erWeiMaResult) {
        if(TextUtils.isEmpty(erWeiMaResult)) {
            ToastUtils.showToast(HandInputActivity.this, "输入不能为空");
            return;
        }
        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("orderid", erWeiMaResult);//86008032893055438199  test
        APIRetrofit.getAPIService().orderGetPosOrderL(RXRequest.getXingPosParams(addParams, this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BlockingBaseObserver<OrderGetPosOrderLEntity>() {
                    @Override
                    public void onNext(OrderGetPosOrderLEntity orderGetPosOrderLEntity) {
                        //                    if (Tools.isAvailable
                        //                    (orderGetPosOrderLEntity)) return;
                        int success = orderGetPosOrderLEntity.getSuccess();
                        if(success == 1) {
                            List<OrderGetPosOrderLEntity.DataBean> data =
                                    orderGetPosOrderLEntity.getData();
                            //会员消费的订单数必须大于0
                            if(data.size() == 0) {
//                                ToastUtils.showToast(HandInputActivity.this, "订单不存在!");
                                tvError.setText("订单不存在！");
                                tvError.setVisibility(View.VISIBLE);
                                return;
                            }

                            OrderGetPosOrderLEntity.DataBean.ListBean listBean =
                                    data.get(0).getList().get(0);
//                            OrderdetailEntity.OrderinfoBean orderinfo =
//                            orderdetailentity.getOrderinfo();

                            if(listBean != null) {
                                Intent intent = new Intent(HandInputActivity.this,
                                        RefoundMoneyDetailActivity.class);
                                intent.putExtra("date", listBean);
//                                intent.putExtra("ordernumber", editContent);
                                startActivity(intent);
                                finish();
                            } else {
                                ToastUtils.showToast(HandInputActivity.this, "订单信息为空");
                            }

                        } else if(success == -100 | success == -200) {
                            //// TODO: 2017/12/9 0009 绑定guid  界面
                            startActivity(new Intent(HandInputActivity.this,
                                    BangGuidActivity.class));
                            finish();
                        } else if(success == -300 || success == -2 || success == -3 || success == -6) {
                            //// TODO: 2017/12/9 0009 去登录的界面
                            com.blankj.utilcode.util.ToastUtils.showShortSafe(orderGetPosOrderLEntity.getErrMsg());
                            //扫码错误，弹出提示且关闭
                            finish();
                        } else {
                            ToastUtils.showToast(HandInputActivity.this,
                                    orderGetPosOrderLEntity.getErrMsg() + "");

                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        if(e instanceof SocketTimeoutException) {
                            Toast.makeText(HandInputActivity.this, "网络连接超时",
                                    Toast.LENGTH_SHORT).show();
                        } else if(e instanceof ConnectException) {
                            Toast.makeText(HandInputActivity.this, "连接失败",
                                    Toast.LENGTH_SHORT).show();
                        } else if(e instanceof UnknownHostException) {
                            Log.e("onError:", "error:-----" + e.getMessage());//R
                            // .string.checknet +
                            Toast.makeText(HandInputActivity.this, "检查网络状态",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Log.e("onError:", "error:" + e.getMessage());//R.string
                            // .checknet +
                            Toast.makeText(HandInputActivity.this, "检查网络状态",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    private void getKoubeiTicket(String strTicketID) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("TicketID", strTicketID);
        APIRetrofit.getAPIService().getKouBeiTicket(RXRequest.getXingPosParams(hashMap,
                HandInputActivity.this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BlockingBaseObserver<KouBeiTicketEntity>() {
                    @Override
                    public void onNext(KouBeiTicketEntity kouBeiTicketEntity) {
                        int success = kouBeiTicketEntity.getSuccess();
                        Log.e(TAG, "onNext: " + success);
                        if(kouBeiTicketEntity.getSuccess() == 1) {
                            Intent intent = new Intent(HandInputActivity.this,
                                    PublicPraiseDetailsActivity.class);
                            intent.putExtra("CurrentPrice",
                                    kouBeiTicketEntity.getData().getCurrentPrice());
                            //购买商品xian价
                            intent.putExtra("EffectDate",
                                    kouBeiTicketEntity.getData().getEffectDate());//生效时间
                            intent.putExtra("ExpireDate",
                                    kouBeiTicketEntity.getData().getExpireDate());//失效时间
                            intent.putExtra("ItemName",
                                    kouBeiTicketEntity.getData().getItemName());//商户名称
                            intent.putExtra("OriginalPrice",
                                    kouBeiTicketEntity.getData().getOriginalPrice());
                            //购买商品原价
                            intent.putExtra("TicketStatus",
                                    kouBeiTicketEntity.getData().getTicketStatus());//券状态
                            intent.putExtra("TicketStatusDesc",
                                    kouBeiTicketEntity.getData().getTicketStatusDesc());//券介绍
                            intent.putExtra("strTicketID", strTicketID);
//                            Log.e(TAG, "onNext: " +);
                            startActivity(intent);
                            finish();
                        } else if(success == -100 | success == -200) {
                            //// TODO: 2017/12/9 0009 绑定guid  界面
                            startActivity(new Intent(HandInputActivity.this,
                                    BangGuidActivity.class));
                            finish();
                        } else if(success == -300 || success == -2 || success == -3 || success == -6) {
                            //// TODO: 2017/12/9 0009 去登录的界面
                            com.blankj.utilcode.util.ToastUtils.showShortSafe(kouBeiTicketEntity.getErrMsg());
                            //扫码错误，弹出提示且关闭
                            finish();
                        } else if(success == -4) {
                            //没有成功
                            String erMsg = kouBeiTicketEntity.getErrMsg();
                            ToastUtils.showToast(HandInputActivity.this, erMsg + "");
                        } else if(success == 0) {
                            com.blankj.utilcode.util.ToastUtils.showShortSafe(kouBeiTicketEntity.getErrMsg());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        if(e instanceof SocketTimeoutException) {
                            Toast.makeText(HandInputActivity.this, "网络连接超时",
                                    Toast.LENGTH_SHORT).show();
                        } else if(e instanceof ConnectException) {
                            Toast.makeText(HandInputActivity.this, "连接失败",
                                    Toast.LENGTH_SHORT).show();
                        } else if(e instanceof UnknownHostException) {
                            Log.e("onError:", "error:-----" + e.getMessage());//R
                            // .string.checknet +
                            Toast.makeText(HandInputActivity.this, "检查网络状态",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Log.e("onError:", "error:" + e.getMessage());//R.string
                            // .checknet +
                            Toast.makeText(HandInputActivity.this, "检查网络状态",
                                    Toast.LENGTH_SHORT).show();
                        }
                        com.blankj.utilcode.util.ToastUtils.showShortSafe(e.getMessage());
                    }
                });
    }

}
